package com.cn.sku.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.cn.dataSource.Constants;
import com.cn.dataSource.DynamicDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicSourceBeanConfig {

    @Resource
    private ApplicationContext applicationContext;

    @Bean
    @ConfigurationProperties("spring.datasource.druid.earth")
    public DataSource earthDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "marsDataSource")
    @ConfigurationProperties("spring.datasource.druid.mars")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.mars", name = "enabled", havingValue = "true")
    public DataSource marsDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource earthDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(Constants.DS_EARTH_NAME, earthDataSource);
        Constants.DS_NAME_LIST.add(Constants.DS_EARTH_NAME);
        setDataSource(targetDataSources, Constants.DS_MARS_NAME, "marsDataSource");
        return new DynamicDataSource(earthDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName        数据源名称
     * @param beanName          bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            DataSource dataSource = (DataSource)applicationContext.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
            Constants.DS_NAME_LIST.add(sourceName);
        } catch (Exception e) {
        }
    }


}
